"""
 -*- coding: utf-8-*-
 @File: api_pet_mgt.py
 @Author: chen
 @time: 2024/01/13/ 11:32
"""
import jsonpath

from api_test.api_po_test.api_business.api_base import BaseApi
from api_test.api_po_test.api_business.api_owner_mgt import OwnerMgtApi


class PetMgtApi(BaseApi):
    def __init__(self):
        super().__init__()
        self.owner = OwnerMgtApi()

    def pet_type(self):
        self.logger.info("获取宠物类型信息")
        path = "/petclinic/api/pettypes"
        resp = self.send("get", path)
        return resp.json()

    def get_type_info(self, pet_type):
        type_data = self.pet_type()
        self.logger.info(f"查询宠物类型{pet_type}的信息")
        exper = f'$..[?(@.name=="{pet_type}")]'
        type_info = jsonpath.jsonpath(type_data, exper)
        if type_info:
            self.logger.info(f"查询宠物类型{pet_type}的信息--->成功")
            return type_info[0]
        else:
            self.logger.info(f"查询宠物类型{pet_type}的信息--->失败")
            return None

    def create_pet(self, first_name, last_name, pet_name, pet_birth, pet_type):
        self.logger.info(f"创建宠物【{pet_name}】")
        owner_id = self.owner.get_owner_id(first_name, last_name)
        path = f"/petclinic/api/owners/{owner_id}/pets"
        owner_info = self.owner.owner_info(first_name, last_name)
        type_info = self.get_type_info(pet_type)
        data = {
            "id": None,
            "owner": owner_info,
            "name": pet_name,
            "birthDate": pet_birth,
            "type": type_info
        }
        resp = self.send("post", path, json=data)
        return resp

    def get_pet_info(self, first_name, last_name, pet_name, pet_birth, pet_type):
        owner_info = self.owner.owner_info(first_name, last_name)
        self.logger.info(f"查询宠物【{pet_name}】的信息")
        exper = f'$..[?(@.name=="{pet_name}" and @.birthDate=="{pet_birth}" and @.type.name=="{pet_type}")]'
        result = jsonpath.jsonpath(owner_info, exper)
        if result:
            self.logger.info(f"查询宠物【{pet_name}】的信息--->成功")
            return result[-1]
        else:
            self.logger.error(f"查询宠物【{pet_name}】的信息--->失败")
            return None


if __name__ == '__main__':
    p0 = PetMgtApi()
    first_name0 = "murong"
    last_name0 = "shaozong"
    pet_name0 = "xiaoqiang"
    pet_birth0 = "2024-01-01"
    pet_type0 = "cat"
    print(p0.get_pet_info(first_name0, last_name0, pet_name0, pet_birth0, pet_type0))
